package cn.virens.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

import redis.clients.jedis.JedisPoolConfig;

/**
 * 配置Spring使用Redis作为缓存
 * 
 * @作者 :loioi
 * @创建时间 :2017年7月17日
 */
@Configuration
@EnableRedisHttpSession
public class SpringCacheRedisConfig {

	@Bean("jedisPoolConfig")
	public JedisPoolConfig jedisPoolConfig() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMinIdle(1);
		config.setMaxIdle(10);
		config.setMaxTotal(10);
		config.setTestOnBorrow(true);
		config.setTestOnReturn(true);
		config.setTestOnCreate(true);
		config.setMaxWaitMillis(15000);
		config.setNumTestsPerEvictionRun(3);
		config.setMinEvictableIdleTimeMillis(300000);
		config.setTimeBetweenEvictionRunsMillis(60000);

		return config;
	}

	@Bean("jedisConnectionFactory")
	public JedisConnectionFactory jedisConnectionFactory(@Qualifier("jedisPoolConfig") JedisPoolConfig poolConfig) {
		JedisConnectionFactory factory = new JedisConnectionFactory();
		factory.setHostName("a.loioi.cn");
		factory.setPassword("loioi");
		factory.setPort(6379);
		factory.setDatabase(0);
		factory.setUsePool(true);
		factory.setTimeout(15000);
		factory.setPoolConfig(poolConfig);

		return factory;
	}

	@Bean("redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(@Qualifier("jedisConnectionFactory") RedisConnectionFactory connectionFactory) {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(connectionFactory);

		return template;
	}

	@Bean("springCacheManager")
	public RedisCacheManager redisCacheManager(@Qualifier("redisTemplate") RedisTemplate<?, ?> redisTemplate) {
		RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);

		Map<String, Long> expires = new HashMap<>();
		expires.put("shiro-authorizationCache", 1 * 60 * 60L);
		expires.put("shiro-authenticationCache", 1 * 60 * 60L);

		redisCacheManager.setExpires(expires);
		redisCacheManager.setDefaultExpiration(24 * 60 * 60L);

		return redisCacheManager;
	}
}
